﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TravelingWebApp.Models;
using TravelingWebApp.Repositories;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting;
using TravelingWebApp.Data;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace TravelingWebApp.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class AdminController : Controller
    {
        private IScenaryRepositories _repo;
        private TravelingContext _context;
        private readonly IHostingEnvironment _hostingEnvironment;

        public AdminController(IScenaryRepositories repo, TravelingContext ctx, IHostingEnvironment hostingEnvironment)
        {
            _repo = repo;
            _context = ctx;
            _hostingEnvironment = hostingEnvironment;
        }

        //================ 景点增删改 =====================
        [HttpGet]
        [Route("ApiTester")]
        public ActionResult ApiTester(string id, string ii)
        {
            return Ok("can you see me?" + id + ii);
        }

        [HttpPost]
        [Route("AddScenary")]
        //[Authorize(Roles = "Administer")]
        public async Task<ActionResult<string>> AddScenaryPost([FromBody]Scenary scenary)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Faild to AddScenaryPost");
                return NotFound("ModelState InValid");
            }
            //if (scenary.PhotoAvatar != null && scenary.PhotoAvatar.Length > 0)
            //{
            //    scenary.ImageMimeType = scenary.PhotoAvatar.ContentType;
            //    scenary.ImageName = Path.GetFileName(scenary.PhotoAvatar.FileName);
            //    using (var memoryStream = new MemoryStream())
            //    {
            //        scenary.PhotoAvatar.CopyTo(memoryStream);
            //        scenary.PhotoFile = memoryStream.ToArray();
            //    }
            //    _context.Add(scenary);
            //    _context.SaveChanges();
            //    return Ok();
            //}
            _context.DbScenaries.Add(scenary);
            await _context.SaveChangesAsync();
            return Ok(Json(new { msg = "Success" }));
        }

        //public IActionResult GetImage(string id)
        //{
        //    Scenary requestedScenary = _repo.GetScenaryById(id);
        //    if (requestedScenary != null)
        //    {
        //        string webRootpath = _hostingEnvironment.WebRootPath;
        //        string folderPath = "\\images\\";
        //        string fullPath = webRootpath + folderPath + requestedScenary.ImageName;
        //        if (System.IO.File.Exists(fullPath))
        //        {
        //            FileStream fileOnDisk = new FileStream(fullPath, FileMode.Open);
        //            byte[] fileBytes;
        //            using (BinaryReader br = new BinaryReader(fileOnDisk))
        //            {
        //                fileBytes = br.ReadBytes((int)fileOnDisk.Length);
        //            }
        //            return File(fileBytes, requestedScenary.ImageMimeType);
        //        }
        //        else
        //        {
        //            if (requestedScenary.PhotoFile.Length > 0)
        //            {
        //                return File(requestedScenary.PhotoFile, requestedScenary.ImageMimeType);
        //            }
        //            else
        //            {
        //                return NotFound();
        //            }
        //        }
        //    }
        //    else
        //    {
        //        return NotFound();
        //    }
        //}

        [HttpPost]
        [Route("EditScenary")]
        //[Authorize(Roles = "Administer")]
        public async Task<ActionResult<string>> Edit(string id, [FromBody]Scenary newScenary)
        {
            if (_context.DbScenaries.Include(c=>c.Id == id) == null)
            {
                return BadRequest(Json(new { msg= "id not found "+id}));
            }
            newScenary.Id = id;
            _context.Entry(newScenary).State = EntityState.Modified;
            await _context.SaveChangesAsync();
            return Ok(Json(new { msg = "Modified success ", newScenary }));
        }

        [HttpGet]
        [Route("DeleteScenary")]
        //[Authorize(Roles = "Administer")]
        public ActionResult<string> DeleteScenary(string id)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Faild to DeleteScenaryPost");
                return NotFound("ModelState InValid");
            }
            _repo.DeleteScenaryById(id);
            _repo.SaveChanges();
            return Ok(Json(new { msg = "Delete success " }));
        }

        // ====================== 公告增删 ==================
        [HttpPost]
        [Route("AddAnnouncement")]
        //[Authorize(Roles = "Administer")]
        public async Task<ActionResult<string>> AddAnnouncement([FromBody]Anoucement anoucement)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Faild to AddAnnouncement");
                return NotFound("ModelState InValid");
            }
            anoucement.Date = DateTime.Now;
            _context.DbAnoucements.Add(anoucement);
            await _context.SaveChangesAsync();

            return Ok(Json(new { msg = "Add success " }));
        }

        [HttpGet]
        [Route("DeleteAnnouncement")]
        //[Authorize(Roles = "Administer")]
        public ActionResult<string> DeleteAnnouncement(string id)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Faild to DeleteScenaryPost");
                return NotFound("ModelState InValid");
            }
            var annoucement = _context.DbAnoucements.SingleOrDefault(c => c.Id == id);
            _context.DbAnoucements.Remove(annoucement);
            _context.SaveChanges();
            return Ok(Json(new { msg = "Delete success " }));
        }

        // ====================== 评论审核 ===================
        [HttpGet]
        [Route("enableComment")]
        //[Authorize(Roles = "Administer")]
        public async Task<ActionResult<string>> EnableComment([FromBody]string id)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Faild to enableComment");
                return NotFound(Json("ModelState InValid"));
            }

            _context.DbComments.Include(b => b.Id).SingleOrDefault(c => c.Id == id).IsValid = true;
            await _context.SaveChangesAsync();

            return Ok(Json("Success"));
        }

        // ====================== 导游增删 ===================
        [HttpPost]
        [Route("AddGuide")]
        //[Authorize(Roles = "Administer")]
        public async Task<ActionResult<string>> AddGuidePost([FromBody]Guide guide)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Faild to AddGuidePost");
                return NotFound(Json("ModelState InValid"));
            }
            _context.DbGuides.Add(guide);
            await _context.SaveChangesAsync();
            return Ok(Json("Success"));
        }

        [HttpPost]
        [Route("DeleteGuide")]
        //[Authorize(Roles = "Administer")]
        public async Task<ActionResult<string>> DeleteGuide(string id)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Faild to DeleteGuide");
                return NotFound("ModelState InValid");
            }
            var guide = _context.DbGuides.SingleOrDefault(c => c.Id == id);
            _context.DbGuides.Remove(guide);
            await _context.SaveChangesAsync();
            return Ok(Json("Success"));
        }

        //[HttpPost]
        //[Route("AddGuideToScenary")]
        //public async Task<ActionResult<string>> AddGuideToScenary(string sid, string gid)
        //{
        //    var scenary = await _context.DbScenaries.Include(b => b.Id).SingleOrDefaultAsync(c => c.Id == sid);
        //    if (scenary == null)
        //    {
        //        return BadRequest(Json("Scenary not found"));
        //    }
        //    var guide = await _context.DbGuides.Include(b => b.Id).SingleOrDefaultAsync(c => c.Id == gid);
        //    if (guide == null)
        //    {
        //        return BadRequest(Json("Guide not found"));
        //    }
        //    _context.Update(scenary);
        //    _context.SaveChanges();
        //    return Ok(Json("OK"));
        //}

    }
}
